package world.member.controller;

import java.sql.SQLException;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import world.member.domain.Member;
import world.member.service.MemberService;



@Controller
@RequestMapping("/member")
public class MemberController {
   
   @Resource(name="memberServiceImpl")
   private MemberService service;
   
   private Member member;
   
   private String memberGrade;
   //private String memberLeave;
   private ModelAndView mv;
   
   //**********************회원가입*****************************
   @RequestMapping(value="/join.do" , method=RequestMethod.POST)
   public String joinMember(HttpServletRequest request,HttpServletResponse response,String phone,String phoneNumber1,String phoneNumber2,String mailAddress, @ModelAttribute Member member){

               //grade,leave 고정값 설정
               //memberGrade = member.getMemberGrade(); DB에서 받아온 값으로?
      //DB 멤버 객체 조회해서 -> 
      
      //통신사 , 010 , 앞번호 , 뒷번호 를 가져와 하나의 String 에 담는다.
      String phoneNumber = phone+phoneNumber1+phoneNumber2;
      String email = member.getEmail()+mailAddress;
      member.setPhoneNumber(phoneNumber);
      member.setEmail(email);
      String id = member.getMemberId();//DB에서 가져온 회원정보의 ID와 비교할 입력받은 ID
      
      try{
      
      service.joinMember(member);   //조회한 객체를 넣는게 아니라 , 입력받은 객체를 넣어야함
      }catch(Exception e){
         e.printStackTrace();
      }
      //3.응답
      return "/index.jsp";
   }
   
   //******************************ID 중복 체크***********************
   @RequestMapping("/idCheck.do")
   public String idCheck(String idCheck, ModelMap map,String phone,String phoneNumber1,String phoneNumber2,String mailAddress){
      String message = null;
      
      try {
         
         member = service.memberById(idCheck);
         
         if(member != null){   //중복된 ID
            message = "중복된 ID 입니다.";
            map.addAttribute("message",message);
         
         }else{   //사용 가능한 ID
            message = "사용 가능한 ID 입니다.";
            map.addAttribute("message",message);
         }
      
      } catch (SQLException e) {
         e.printStackTrace();
      }
      
      
      return "jsonView";
   }
   

   
   //******************************로그인*****************************
   
   @RequestMapping(value="/login.do" , method=RequestMethod.POST)
   public ModelAndView loginMember(HttpServletRequest request,HttpServletResponse response,HttpSession session){
      
      String id = request.getParameter("id");
      String password = request.getParameter("password");
      String message = null;
      Member member = null;
      //DB에서 모든 회원 정보를 가져옴
       try {
         member = service.memberById(id);   //회원정보 조회
         String mlt = "mlt";
         session = request.getSession(); //세션 생성
         
         if(id.equals(member.getMemberId())){
            if(password.equals(member.getMemberPassword())){   //로그인 성공
            	if(mlt.equals(member.getMemberLeave())){	//탈퇴여부 : mlt
            		
               session.setAttribute("login_member", member);
               mv = new ModelAndView("/main.jsp");
            	
            	}else{	//탈퇴여부 : mlf
            		message = "탈퇴한 회원 입니다.";
            		request.setAttribute("message", message);
            		mv = new ModelAndView("/member/error.jsp");
            	}
            }else{ //패스워드 틀림
               message = "패스워드 틀렸음";
               request.setAttribute("message",message);
               mv = new ModelAndView("/member/error.jsp");
            }
         }else{ //ID 틀림
            message = "ID 틀렸음";
            request.setAttribute("message",message);
            mv = new ModelAndView("/member/error.jsp");
         }
      } catch (Exception e) {
         message = "없는 ID 입니다.";
         request.setAttribute("message", message);
         mv = new ModelAndView("/member/error.jsp");
         e.printStackTrace();
      }
       return mv;
   }
   

	//******************************닉네임 중복 체크***********************
	@RequestMapping("/nickNameCheck.do")
	public String nickNameCheck(String nickNameCheck, ModelMap map){
		String message = null;
		
		try {
			
			member = service.nickNameCheck(nickNameCheck);
			
			if(member != null){//중복
				message = "중복된 닉네임 입니다.";
				map.addAttribute("message",message);
			}else{//사용 가능
				message = "사용 가능한 닉네임 입니다.";
				map.addAttribute("message",message);
			}
			
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		return "jsonView";
	}
	
	
	
	//**************************로그아웃***********************************
	@RequestMapping("/logout.do")
	public String logoutMember(HttpSession session){
			
			session.invalidate();
		
			return "/main.jsp";
	}
	
	//***********************회원 탈퇴*******************************
	@RequestMapping("/delete.do")
	public ModelAndView deleteMember(HttpSession session){
		
		
			
			Object obj = session.getAttribute("login_member");
			Member member = (Member) obj;
			member.setMemberLeave("mlf");//세션 수정
			System.out.println("탈퇴여부 : "+member);
			System.out.println("세션정보 : "+session.getAttribute("login_member"));
			
		try {
			//수정
			service.updateLeave(member);	//매개변수 = 세션정보
			session.invalidate();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	
		return new ModelAndView("/main.jsp");
	}



   //*******************************update page 이동***************

   
   //*******************************update**************************
   @RequestMapping(value="/update.do" , method=RequestMethod.POST)
   public String updateMember(HttpServletRequest request,HttpSession session){
	      
	      Object obj = session.getAttribute("login_member");
	      Member member = (Member) obj;//로그인 한 회원정보
	      //String [] str = null;
	      //member.getPhoneNumber().split("-");
	      
	      //전화번호 수정
	      String phone = request.getParameter("phone");
	      String phoneNumber1 = request.getParameter("phoneNumber1");
	      String phoneNumber2 = request.getParameter("phoneNumber2");
	      String allPhoneNumber = phone+phoneNumber1+phoneNumber2;
	      
	      //email 수정
	      String email = request.getParameter("email");
	      String mailAddress = request.getParameter("mailAddress");
	      String allEmail = email+mailAddress;
	      //수정된 값
	      String password = request.getParameter("memberPassword");
	      String nickName = request.getParameter("nickName");
	   
	      

	      //수정된 값 저장
	      member.setMemberPassword(password);
	      member.setNickName(nickName);
	      member.setEmail(allEmail);
	      member.setPhoneNumber(allPhoneNumber);

	      try {
	         service.updateMember(member);
	         
	      } catch (SQLException e) {
	         // TODO Auto-generated catch block
	         e.printStackTrace();
	      }

	      return "/main.jsp";
	      
	   }
}